package mn.more.wits.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import mn.more.wits.client.ExamSessionManager;
import mn.more.wits.client.dto.ExamListDTO;
import mn.more.wits.client.dto.Payload;
import mn.more.wits.client.exception.InvalidExamActionException;
import mn.more.wits.client.exception.InvalidExamTestException;
import mn.more.wits.server.dao.ExamListingDAO;
import mn.more.wits.server.model.ExamTaker;
import mn.more.wits.server.model.WitsUser;
import mn.more.wits.server.util.ClientModelEncryptor;
import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;

/** RPC to coordinate an exam with a {@link ExamTaker}. */
public class ExamSessionManagerImpl extends RemoteServiceServlet implements ExamSessionManager {

	private ExamListingDAO dao;
	private ClientModelEncryptor clientModelEncryptor;
	private transient MessageSource messages;
	private transient Logger logger = Logger.getLogger(ExamSessionManagerImpl.class);

	public void setDao(ExamListingDAO dao) { this.dao = dao; }

	public void setClientModelEncryptor(ClientModelEncryptor clientModelEncryptor) {
		this.clientModelEncryptor = clientModelEncryptor;
	}

	public void setMessages(MessageSource messages) { this.messages = messages; }

	public Payload getAvailableExams() {
		WitsUser user = SecurityUtil.getCurrentUser();
		if (user == null) {
			logger.error("No valid user in session");
			return null;
		}

		if (!(user instanceof ExamTaker)) {
			logger.error("Invalid user type '" + user.getMainRoleName() + "' encountered, expect ExamTaker");
			return null;
		}

		ExamListDTO examList = dao.listAvailableExams((ExamTaker) user);
		if (logger.isDebugEnabled()) {
			logger.debug("examList.getSummaries().length = " + examList.getSummaries().length);
		}
		Payload payload = clientModelEncryptor.toPayload(examList);
		return payload;
	}

	public Payload init(Payload testId) throws InvalidExamTestException {
		return null;
	}

	public Payload getFirstQuestion() {
		return null;
	}

	public Payload sendAnswerAndGetQuestion(Payload answer) throws InvalidExamActionException {
		return null;
	}

	public Payload complete() throws InvalidExamActionException {
		return null;
	}

	public Payload forfeit() throws InvalidExamActionException {
		return null;
	}
}